package net.edu_soft.ec.asset.controller;

import net.edu_soft.ec.asset.pojo.UserInfo;
import net.edu_soft.ec.asset.pojo.UserInfoExample;
import net.edu_soft.ec.asset.service.UserInfoService;
import net.edu_soft.ec.common.util.MailService;
import net.edu_soft.ec.common.util.PuingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @Description: 用户信息控制类
 * @author puing
 * @date 2019年12月6日
 */

//@CrossOrigin(value = "http://localhost:8080",allowCredentials = "true")//解决携带cookie
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private MailService mailService;

    /**
     * 用户注册

     * @param email
     * @param pwd
     * @param yzm
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/register")
    public Map<String,Object> register(HttpSession session,String email, String pwd, String yzm) throws Exception {
        Enumeration e = session.getAttributeNames();

        int num = 0;

        while(e.hasMoreElements()){

            e.nextElement();

            num++;

        }

        System.out.println("session的个数：" + num);
        System.out.println("************************"+session.toString()+"*************************"+session.getId());

        Map<String, Object> map = new HashMap<>();
        System.out.println("提交信息：账号："+email+"验证码："+yzm+"注册的密码："+pwd);
        String msg="ok";
        if(email==null||email.equals("")||pwd==null||pwd.equals("")||yzm==null||yzm.equals("")){
            map.put("msg","填写完整信息");
            return map;
        }
        if(pwd.length()<6) {
            map.put("msg", "密码最少六位数");
            return map;
        }
        String yzm1 = (String) session.getAttribute(email);
        String email1 = (String) session.getAttribute(yzm);
        System.out.println("获取存入的session信息：email："+email1+"验证码："+yzm1);
        session.removeAttribute(email);
        session.removeAttribute(yzm);
        //1.检验验证码是否正确
        if(yzm.equals(yzm1)&&email.equals(email1)){
            //2.检验该邮箱是否已经注册
            UserInfoExample setemal=new UserInfoExample();
            UserInfoExample.Criteria createCriteria = setemal.createCriteria();
            createCriteria.andEmailEqualTo(email);
            List<UserInfo> userinformataion=userInfoService.selectByExample(setemal);
            if (userinformataion.size()!=0){
                map.put("msg", "该账号已经注册");
                System.out.println("该账号已经注册");
                return map;
            }
            //3.注册
            UserInfo userinfo=new UserInfo();
            String salt = PuingUtil.getRandomIdByUtil();//16位随机码
            userinfo.setEmail(email);
            userinfo.setPassword(PuingUtil.getMD5Value(pwd,salt));
            userinfo.setUsername(email);
            userinfo.setSalt(salt);
            userinfo.setRandomId(PuingUtil.generateShortUuid());//生成8位UUID大写随机码
            long time1=System.currentTimeMillis();
            Date date1=new Date(time1);
            userinfo.setBirthDate(date1);
            userinfo.setCreateDate(date1);
            userinfo.setStatus(0);
            int styic=userInfoService.insertSelective(userinfo);
            if (styic!=1){
                msg="注册失败";
            }
        }else{
            msg="验证码不正确";
        }
        map.put("msg", msg);
        return map;
    }


    /**
     * 获取验证码
     * @param email
     * @param session
     * @return
     */
    @RequestMapping(value = "/sendCode")
    public Map<String,Object> sendCode(String email, HttpSession session){
        Map<String, Object> map = new HashMap<>();
        String msg="ok";
        //1.检验该账号是否注册
        UserInfoExample setemal=new UserInfoExample();
        UserInfoExample.Criteria createCriteria = setemal.createCriteria();
        createCriteria.andEmailEqualTo(email);
        List<UserInfo> userinformataion=userInfoService.selectByExample(setemal);
        if (userinformataion.size()!=0){
            map.put("msg", "该账号已经注册");
            System.out.println("该账号已经注册");
            return map;
        }
        //2.随机生成效验
        String yzm = String.valueOf(new Random().nextInt(899999) + 100000);
        //3.使用session保存账号和效验码
        session.setAttribute(email,yzm);
        session.setAttribute(yzm,email);
        session.setMaxInactiveInterval(30*60);
        //4.向该邮箱发送邮件
        String message = "您当前的验证码为："+yzm;
        //System.out.println(message);
        System.out.println("获取验证码****************************************"+session.getId());
        System.out.println("存入session的值为：yzm:"+session.getAttribute(email)+"emall:"+(String) session.getAttribute(yzm)+"session" +
                "id:"+session.getId());
        try {
            mailService.sendAttachmentsMail(email, "[高教云服务平台]", message);
        }catch (Exception e){
            msg="发送失败";
        }
        map.put("msg", msg);
        return map;
    }


    /**
     * 用户登录
     * @param email
     * @param pwd
     * @param session
     * @return
     */
    @RequestMapping(value = "/login")
    public Map<String,Object> login(String email,String pwd, HttpSession session){
        System.out.println("当前输入的用户名："+email+"密码："+pwd);
        Map<String, Object> map = new HashMap<>();
        String msg = "ok";

        //1.检验该账号是否注册
        UserInfoExample setemal=new UserInfoExample();
        UserInfoExample.Criteria createCriteria = setemal.createCriteria();
        createCriteria.andEmailEqualTo(email);
        List<UserInfo> userinformataion=userInfoService.selectByExample(setemal);
        if (userinformataion.size()!=0){
            System.out.println("获取到的信息："+userinformataion);
            //2.检验密码是否正确
            if (userinformataion.get(0).getPassword().equals(pwd)){
                //3.登录
                map.put("user",userinformataion);
                session.setAttribute("account",userinformataion.get(0));
            }else {
                msg="账号或密码错误";
            }
        }else {
            msg = "账号或密码错误（账号未注册）";
        }
        map.put("msg", msg);
        return map;
    }
}
